package com.zhengbing.tj.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 * JWT工具类，提供令牌生成、解析和验证功能
 * 使用HMAC-SHA256算法进行签名，通过SHA-256哈希处理密钥确保符合安全长度要求
 * 需在application.properties中配置jwt.secret和jwt.expiration参数
 * 
 * @author zhengbing
 * @date 2025-07-29
 */
@Component
public class JwtUtils {

    @Value("${jwt.secret}")
    private String secretKey;

    @Value("${jwt.expiration}")
    private long expirationTime;

    private Key getSigningKey() {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] keyBytes = digest.digest(secretKey.getBytes(StandardCharsets.UTF_8));
            return Keys.hmacShaKeyFor(keyBytes);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Failed to generate signing key", e);
        }
    }

    public long getExpirationTime() {
        return expirationTime;
    }

    /**
     * 从token中获取用户名
     */
    public String getUsernameFromToken(String token) {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 解析token获取Claims
     */
    private Claims parseToken(String token) {
        try {
            Key key = getSigningKey();
            return Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (ExpiredJwtException e) {
            throw new RuntimeException("token已过期");
        } catch (JwtException e) {
            throw new RuntimeException("无效的token: " + e.getMessage());
        } catch (Exception e) {
            throw new RuntimeException("token解析失败: " + e.getMessage());
        }
    }

    /**
     * 验证token是否过期
     */
    public boolean isTokenExpired(String token) {
        Claims claims = parseToken(token);
        Date expiration = claims.getExpiration();
        return expiration.before(new Date());
    }

    /**
     * 验证token是否有效
     * @param token JWT令牌
     * @param username 预期的用户名
     * @return 如果token有效且用户名匹配则返回true，否则返回false
     */
    public boolean validateToken(String token, String username) {
        try {
            Claims claims = parseToken(token);
            String subject = claims.getSubject();
            return subject.equals(username) && !isTokenExpired(token);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 生成JWT token
     */
    public String generateToken(String username) {
        Key key = getSigningKey();
        Date now = new Date();
        Date expirationDate = new Date(now.getTime() + expirationTime);

        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(now)
                .setExpiration(expirationDate)
                .signWith(key)
                .compact();
    }
}